package com.bloveoacom.http;

import com.bloveoacom.exception.ApiException;
import com.bloveoacom.util.GsonUtil;
import com.bloveoacom.weichi.bean.BaseBean;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * author: yjl
 * e-mail: 1271901673@qq.com
 * time  : 2018/10/10
 * desc  :
 */
final class MyGsonResponseBodyConverter<T> implements Converter<ResponseBody,T>{
    private Gson gson;
    private Type type;

    public MyGsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            BaseBean baseBean = gson.fromJson(response,BaseBean.class);
            if (!baseBean.isOk()) {
                throw new ApiException(baseBean.code, baseBean.msg);
            }
            return gson.fromJson(response,type);
        }finally {
            value.close();
        }
    }
}
